<template>
    <container type="simple" class="g-width100 g-height100"  aside-style="width:320px;" main-style="padding:0px;">
        <div slot="header">

            <Form
                    inline
                    ref="form"
                    :form-items="formItems"
                    v-on:formChange="(form)=>{selectedAppCode = form.appCode}"
            ></Form>

        </div>
        <div slot="main" class="g-width100 g-height100">
            <el-alert
                    title="在添加个性化菜单前请确认已经设置自定义菜单"
                    type="warning"
                    show-icon>
            </el-alert>
            <template v-for="(item ,index) in buttons">
                <MpMenuEdit

                        :show-match-rule-form="true"
                        :key="index"
                        :buttons="item.button"
                        :app-code="selectedAppCode"
                        :switch-to-origin-wx-mp-menu-json="(btns)=>{
                        return conditionalMenuSwitchToOriginWxMpMenuJson(btns,$refs.matchRuleForm[index].getFormData())
                        }"
                >

                    <Form

                            ref="matchRuleForm"
                            :key="index"
                            :form-data="item.matchrule"
                            :form-items="matchRuleFormItems(index)"
                    ></Form>
                </MpMenuEdit>
            </template>

        </div>
    </container>
</template>

<script>
    import Container from '../../../../../common-util/src/components/page/Container.vue'
    import Form from '../../../../../common-util/src/components/page/Form.vue'
    import MpMenuEdit from '../../../components/mp/MpMenuEdit.vue'
    export default {
        components:{
            Form,
            MpMenuEdit,
            Container
        },
        name: "MpSelfConditionalMenu",
        computed:{

        },
        data(){
            return {
                buttons: [],
                selectedAppCode: null,
                formItems:[
                    {
                        field: {
                            name: 'appCode'
                        },
                        element:{
                            type: 'select',
                            required: true,
                            select:{
                                url: this.$baseURL.wx + '/wx/mp/config/list',
                                optionProp:{
                                    value: 'appCode',
                                    label: 'appName'
                                }
                            },
                            label: '公众号',
                        }
                    },
                    {
                        element:{
                            type: 'button',
                            button:[
                                {
                                    action: this.menuGet,
                                    code: 'wx_mp_menu_get',
                                    label: '获取个性化菜单'
                                },
                                {
                                    action: this.addConditionalMenu,
                                    label: '添加性化菜单'
                                }
                            ]
                        }
                    },
                ],

            }
        },
        mounted(){
        },
        methods:{
            getAppCode(){
                return this.$refs.form.getFormData().appCode
            },
            matchRuleFormItems (index) {
                return [
                    // 该项不是匹配规则，仅用来删除
                    {
                        field:{
                            name: 'menuid'
                        }
                    },
                    {
                        field: {
                            name: 'tag_id'
                        },
                        element:{
                            placeholder: '用户标签的id，可通过用户标签管理接口获取',
                            label: '用户标签id',
                        }
                    },
                    {
                        field: {
                            name: 'sex'
                        },
                        element:{
                            type: 'selectLocal',
                            selectLocal:{
                                data:[
                                    {
                                        id: '1',
                                        name: '男'
                                    },
                                    {
                                        id: '2',
                                        name: '女'
                                    }
                                ]
                            },
                            label: '性别',
                        }
                    },
                    {
                        field: {
                            name: 'country'
                        },
                        element:{
                            placeholder: '中国',
                            label: '国家',
                            required: (form)=> {return form.province},
                        }
                    },
                    {
                        field: {
                            name: 'province'
                        },
                        element:{
                            placeholder: '北京',
                            required: (form)=> {return form.city},
                            label: '省份',
                        }
                    },
                    {
                        field: {
                            name: 'city'
                        },
                        element:{
                            placeholder: '北京',
                            label: '城市',
                        }
                    },
                    {
                        field: {
                            name: 'client_platform_type'
                        },
                        element:{
                            type: 'selectLocal',
                            selectLocal:{
                                data:[
                                    {
                                        id: 'IOS',
                                        name: '苹果'
                                    },
                                    {
                                        id: 'Android',
                                        name: '安卓'
                                    },
                                    {
                                        id: 'Others',
                                        name: '其它'
                                    }
                                ]
                            },
                            label: '客户端版本',
                        }
                    },
                    {
                        field: {
                            name: 'language'
                        },
                        element:{
                            placeholder: '语言信息，是用户在微信中设置的语言1、简体中文 "zh_CN" 2、繁体中文TW "zh_TW" 3、繁体中文HK "zh_HK"',
                            label: '语言',
                        }
                    },
                    {
                        element:{
                            type: 'button',
                            button:[
                                {
                                    action: ()=>{this.menuDelete(index)},
                                    code: 'wx_mp_conditional_menu_delete',
                                    label: '删除当前个性化菜单'
                                },
                                {
                                    action: 'reset',
                                    label: '重置'
                                }
                            ]
                        }
                    },
                ]
            },
            // 获取自定义菜单(高级)
            menuGet(){
                this.$refs.form.validateAndSubmitForm((form)=>{
                    this.$refs.form.setButtonLoading('wx_mp_menu_get',true)
                    this.axios.get(this.$baseURL.wx + '/wx/mp/menu/' + form.appCode + '/getOrigin')
                        .then(res => {
                            if(!res.data){
                                this.$message.error("未获取到数据，请确认已设置了自定义菜单")
                            }else if(res.data.conditionalmenu){
                                this.buttons = this.conditionalmenuSubButtonAdapt(res.data.conditionalmenu || [{button:[]}])
                            }else{
                                this.$message.error("当前公众号未设置过个性化菜单，你可以先添加个性化菜单")
                            }

                        }).catch(error => {
                        if(error.response){
                            if(error.response.status == 401){
                                return
                            }
                            this.$message.error(error.response.data.msg)
                        }else {
                            this.$message.error('网络错误或服务不可用')
                        }
                    }).finally(()=>{
                        this.$refs.form.setButtonLoading('wx_mp_menu_get',false)
                    })
                })
            },
            conditionalmenuSubButtonAdapt(buttons){
                buttons.forEach((buttonsItem)=>{
                    let button = buttonsItem.button
                    button.forEach((item)=>{
                        if(item.sub_button){
                            item.sub_button ={
                                list: item.sub_button
                            }
                        }
                    })
                })

                return buttons
            },
            menuDelete(index){
                let appCode = this.getAppCode()
                if(!appCode){
                    this.$message.error('请选择需要删除的公众号')
                    return
                }
                this.$confirm('确定要删除吗, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let menuId = this.buttons[index].menuid

                    if(!menuId){
                        this.buttons.splice(index,1)
                        this.$message.success('删除成功,当前菜单未同步到微信服务器')
                        return
                    }
                    this.$refs.form.setButtonLoading('wx_mp_conditional_menu_delete',true)
                    this.axios.delete(this.$baseURL.wx + '/wx/mp/menu/' + appCode + '/delete/' + menuId)
                        .then(res=>{
                            this.buttons.splice(index,1)
                            this.$message.success('删除成功,已从微信服务器删除')
                        }).catch(error=>{
                        if(error.response){
                            if(error.response.status == 401){
                                return
                            }
                            this.$message.error(error.response.data.msg)
                        }else {
                            this.$message.error('网络错误或服务不可用')
                        }
                    })
                        .finally(()=>{
                        this.$refs.form.setButtonLoading('wx_mp_conditional_menu_delete',false)
                    })
                })
            },
            addConditionalMenu(){
                this.buttons.push({button:[]})
            },
            // 将自定义菜单的数据结构转为微信公众号原始的可提交的json数据
            conditionalMenuSwitchToOriginWxMpMenuJson(buttons,matchRule){
                let originMenu = {
                    button: [],
                    matchrule: matchRule
                }
                let allEmpty = true
                for (let key in matchRule) {
                    // 排队menuid
                    if(matchRule[key]){
                        allEmpty = false
                    }
                }
                if(allEmpty){
                    this.$message.error("匹配规则不能全部为空")
                    return false
                }
                let generateButtonItem = (buttonsItem)=>{
                    let buttonItem = {}
                    for (let key in buttonsItem){
                        if(buttonsItem[key] !== null){
                            if(key == 'sub_button'){
                                if(buttonsItem[key].list != null){
                                    buttonItem['sub_button'] = []
                                    for (let i = 0; i < buttonsItem[key].list.length; i++) {
                                        buttonItem['sub_button'].push(generateButtonItem(buttonsItem[key].list[i]))
                                    }
                                }
                            }
                            else{
                                buttonItem[key] = buttonsItem[key]
                            }
                        }
                    }
                    return buttonItem
                }
                for (let i = 0; i < buttons.length; i++) {
                    let buttonsItem = buttons[i]
                    originMenu.button.push(generateButtonItem(buttonsItem))
                }
                return originMenu
            }

        }
    }
</script>

<style scoped>

</style>